import type { LoginResponse } from '@/api/account';
import { useAppStore } from '@/pinia/app';
import { getUserInfoAxios, queryBaseDictInfoAxios } from '@/api/user';

/** 跳转到对应的页面 */
export function openPage() {
  //如果登录了就直接跳转
  const pages = getCurrentPages();
  // 登录成功后，跳转到登录前的页面 (只有上一个路由不为登录页面才返回，否则就跳转到首页)
  const loginRoute = 'pages/account/login/login';
  const prevPageRoute = pages[pages.length - 2]?.route || ''; // 上一个页面
  if (pages.length >= 2 && prevPageRoute.indexOf(loginRoute) !== 0) {
    uni.navigateBack();
  } else {
    uni.switchTab({ url: '/pages/tab-bar/index1/index1' });
  }
}

/** 设置登录后的信息 */
export async function setLoginInfo(data: LoginResponse): Promise<boolean> {
  const appStore = useAppStore();
  try {
    appStore.setIsLoginLoging(true);
    data && appStore.setAccessToken(data.accessToken || '');
    data && appStore.setRefreshToken(data.refreshToken || '');
    data && appStore.setPrivateKeyStr(data.privateKeyStr || '');
    const [userRes, dictRes] = await Promise.all([getUserInfoAxios(data.accessToken), queryBaseDictInfoAxios()]);
    appStore.setUserInfo(userRes.data);
    appStore.setBaseDictInfo(dictRes.data);
    appStore.setIsLoginLoging(false);
    openPage();
    appStore.setIsManualExit(false);
    return Promise.resolve(true);
  } catch (error) {
    appStore.setIsLoginLoging(false);
    return Promise.reject(error);
  }
}
